﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SQLite;
using WisdriContacts.Model;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WisdriContacts
{
    using System.ComponentModel;

    public partial class UpdatePage : PhoneApplicationPage
    {
        public UpdatePage()
        {
            InitializeComponent();

            DataContext = App.ViewModel;
        }


        /*
                private async void CheckVersion_Click(object sender, RoutedEventArgs e)
                {
                    bool isActived;
                    IsolatedStorageSettings.ApplicationSettings.TryGetValue<bool>("IsActived", out isActived);
                    if (!isActived)
                    {
                        MessageBox.Show("请先激活");
                        return;
                    }


                }
        */

        private void UpdatePage_OnLoaded(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (!settings.Contains("version"))
            {
                settings.Add("version", "20150504");
                settings.Save();
            }

            CurrentVersionTextBlock.Text = settings["version"].ToString();

        }

        private async void Update_Click(object sender, RoutedEventArgs e)
        {
            bool isActived;
            IsolatedStorageSettings.ApplicationSettings.TryGetValue<bool>("IsActived", out isActived);
            if (!isActived)
            {
                MessageBox.Show("请先激活");
                return;
            }

            try
            {
                var requestVersion =
                    WebRequest.Create("http://kidfruit.github.io/WisdriContacts/LatestDataVersion.txt?" + Guid.NewGuid().ToString());

                requestVersion.Method = "GET";
                WebProgressBar.Visibility = Visibility.Visible;
                UpdateButton.Content = "正在更新";
                UpdateButton.IsEnabled = false;

                using (var response = await requestVersion.GetResponseAsync())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            var receive = sr.ReadToEnd();

                            LatestVersionTextBlock.Text = receive;
                        }
                    }
                }


                if (!string.IsNullOrEmpty(LatestVersionTextBlock.Text.Trim())
                    && CurrentVersionTextBlock.Text != LatestVersionTextBlock.Text)
                {
                    MessageBox.Show("开始更新");

                    var request = WebRequest.Create(
                        "http://kidfruit.github.io/WisdriContacts/data.txt?" + Guid.NewGuid().ToString());
                    request.Method = "GET";
                    using (var response = await request.GetResponseAsync())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {

                            int count = 0;
                            long length = responseStream.Length;
                            byte[] receiveStream = new byte[length];
                            WebProgressBar.IsIndeterminate = false;
                            WebProgressBar.Value = 0;
                            WebProgressBar.Maximum = length;
                            WebProgressBar.Minimum = 0;
                            while (true)
                            {
                                int num = await responseStream.ReadAsync(receiveStream, count, 1000);
                                if (num == 0) break;

                                count += num;
                                WebProgressBar.Value = count;
                            }

                            var receive = Encoding.UTF8.GetString(receiveStream, 0, (int)length);

                            var byteValue = Convert.FromBase64String(receive);
                            string decodeReceive = Encoding.UTF8.GetString(byteValue, 0, byteValue.Length);

                            var personList = JsonConvert.DeserializeObject<List<PERSON>>(decodeReceive);


                            using (SQLiteConnection conn = new SQLiteConnection(App.ViewModel.DB_PATH))
                            {
                                try
                                {
                                    conn.BeginTransaction();


                                    SQLiteCommand command = new SQLiteCommand(conn);

                                    command.CommandText = "delete from PERSON";
                                    int oldDataCount = command.ExecuteNonQuery();
                                    MessageBox.Show(string.Format("旧数据有{0}条", oldDataCount));

                                    conn.Commit();
                                    command.CommandText = @"DROP TABLE [PERSON];";
                                    command.ExecuteNonQuery();
                                    command.CommandText = @"CREATE TABLE [PERSON] (
                                          [ID] nvarchar(2147483647) NOT NULL
                                        , [NAME] nvarchar(2147483647) NULL
                                        , [DEPARTMENT] nvarchar(2147483647) NULL
                                        , [MOBILE_PHONE] nvarchar(2147483647) NULL
                                        , [VIRTUAL_PHONE] nvarchar(2147483647) NULL
                                        , [POSITION] nvarchar(2147483647) NULL
                                        , [REGION] nvarchar(2147483647) NULL
                                        , [OFFICE_PHONE] nvarchar(2147483647) NULL
                                        , [INNER_PHONE] nvarchar(2147483647) NULL
                                        , [PY] nvarchar(2147483647) NULL
                                        , [CAR] nvarchar(2147483647) NULL
                                        , CONSTRAINT [sqlite_autoindex_PERSON_1] PRIMARY KEY ([ID])
                                        );";
                                    command.ExecuteNonQuery();

                                    conn.BeginTransaction();

                                    foreach (var person in personList)
                                    {
                                        command.CommandText = string.Format(
                                            @"INSERT INTO [PERSON]
                                                                                       ([ID]
                                                                                       ,[NAME]
                                                                                       ,[DEPARTMENT]
                                                                                       ,[MOBILE_PHONE]
                                                                                       ,[VIRTUAL_PHONE]
                                                                                       ,[POSITION]
                                                                                       ,[REGION]
                                                                                       ,[OFFICE_PHONE]
                                                                                       ,[INNER_PHONE]
                                                                                       ,[PY]
                                                                                       ,[CAR])
                                                                                   VALUES
                                                                                       ('{0}'
                                                                                       ,'{1}'
                                                                                       ,'{2}'
                                                                                       ,'{3}'
                                                                                       ,'{4}'
                                                                                       ,'{5}'
                                                                                       ,'{6}'
                                                                                       ,'{7}'
                                                                                       ,'{8}'
                                                                                       ,'{9}'
                                                                                       ,'{10}')",
                                            person.ID,
                                            person.NAME,
                                            person.DEPARTMENT,
                                            person.MOBILE_PHONE,
                                            person.VIRTUAL_PHONE,
                                            person.POSITION,
                                            person.REGION,
                                            person.OFFICE_PHONE,
                                            person.INNER_PHONE,
                                            person.PY,
                                            person.CAR);
                                        command.ExecuteNonQuery();
                                    }


                                    CurrentVersionTextBlock.Text = LatestVersionTextBlock.Text;


                                    command.CommandText = "select count(ID) from PERSON";
                                    int newDataCount = command.ExecuteScalar<int>();
                                    MessageBox.Show(string.Format("新数据有{0}条", newDataCount));

                                    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                                    settings["version"] = LatestVersionTextBlock.Text;
                                    settings.Save();

                                    conn.Commit();

                                    MessageBox.Show("更新完毕");
                                }
                                catch (Exception ex)
                                {
                                    conn.Rollback();
                                    MessageBox.Show(ex.Message);
                                }
                            }

                        }
                    }

                    App.ViewModel.LoadData();

                }
                else
                {
                    MessageBox.Show("无需更新");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                UpdateButton.IsEnabled = true;
                UpdateButton.Content = "更新数据";
                WebProgressBar.Visibility = Visibility.Collapsed;


            }
        }
    }

    [DataContract]
    public class Info
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string NAME { get; set; }
    }
}